//界面初始化值
var reloadFlag = true;
var fileName = "";
var isDebug = false;
var scrollamount = 5;
var showModul = "PCT_TV_SHOW";
var un = localStorage.getItem('un');
var pw = localStorage.getItem('pw');
var serverUrl = localStorage.getItem('serverUrl');
var serverIp = localStorage.getItem('serverIp');
var serverPort = localStorage.getItem('serverPort');
var serverProject = localStorage.getItem('serverProject');

var type = "workCenter";
var workCenterGid = localStorage.getItem('workcenterGid');
var workCenterCode = localStorage.getItem('workcenterCode');
var workCenterName = localStorage.getItem('workcenterName');
var userName = localStorage.getItem('un');
var nowDate;
var siteGid = '2c942a6a50c620400150c62b5814000a';
var siteCode = '01';
var siteName = '金属事业部';
var typeSite = "factory";
//消息重连定时器对象
var webSocketTimer = null;
//消息url前半段
var msgUrl = "ws://" + serverIp + ":" + serverPort + "/" + serverProject + "/webmsg/";
//消息socket
var socket = atmosphere;
var equipLineChart;
var myChart2;

apiready = function() {
	//工作中心赋值
	$("#workCenterName").html("线体："+workCenterName);
	//初始化数据
	getRemoteData();
	myChart2 = echarts.init(document.getElementById('qualityPer'));
	equipLineChart = echarts.init(document.getElementById('equipLine'));
}

// 质量指标
function uqcChartInit(data) {
	var option2 = {
		tooltip : {
			trigger : 'axis',
			axisPointer : {
				type : 'shadow'
			}
		},
		legend : {
			data : data.legend
		},
		toolbox : {
			show : true,
			orient : 'vertical',
			y : 'center',
			feature : {
			}
		},
		calculable : true,
		xAxis : [{
			type : 'category',
			axisLabel : {
				'interval' : 0
			},
			data : data.xAxis
		}],
		yAxis : [{
			type : 'value',
			splitArea : {
				show : true
			}
		}],
		grid : {
			bottom: '40%',
			top : '20%'			
			
		},
		series : data.series2
	};
	// 为echarts对象加载数据
	myChart2.setOption(option2);
}

//获取副屏数据
function getRemoteData() {
	//创建日志文件
//	fileName = new Date().toString()+".txt";
//	alert(fileName);
//	var fs = api.require('fs');
//	fs.createFile({
//	    path: 'fs://'+fileName
//	}, function(ret, err) {
//	    if (ret.status) {
//	        alert(JSON.stringify(ret));
//	    } else {
//	        alert(JSON.stringify(err));
//	    }
//	});
	var url = "http://" + serverIp + ":" + serverPort + "/" + serverProject
			+ "/autoLoginController!login.m?_u=" + un + "&_p=" + pw
			+ "&_to=pctLayoutController!getShowData.m&type=" + type
			+ "&typeKey=" + workCenterGid + "&typeValue=" + workCenterCode
			+ "&userName=" + userName + "&layoutShow=" + showModul;
			api.ajax({
					url : url,
					method : 'post',
					dataType : 'json',
					data : {
						values : {
							nowTime : new Date()
						}
					}
			}, function(ret, err) {
			var data = eval(ret);
			
			nowDate = data.nowDate;
			scrollamount = data.scrollamount;
			var equipStatusKanbanDataMap = data.equipStatusKanbanDataMap;
			var equipOEEDataMap = data.equipOEEDataMap;
			var equipOp = data.equipOp;
			
			//机型
			var mrl = data.mrl;
			if(checkNull(mrl)){
				setEquipType(mrl);
			}
			
			//通知模板
			var tvState = data.tvState;
			setTvStata(tvState);
			var tvContent = data.tvContent;
			if(data.syncTvContent)
				setTvContent(tvContent);

			//设备状态
			var stateMap = data.stateMap;
			if(checkNull(stateMap))
				setEquipmentState(stateMap);
	
			//质量指标
			var uqcDataMap = data.uqcDataMap;
			if(checkNull(uqcDataMap))
				uqcChartInit(uqcDataMap);

			//异常警报(查询一条最近的异常信息)
			/*var unusualAlarmMap2 = data.unusualAlarmMap;
			if(checkNull(unusualAlarmMap2))
			   setLiValue2(unusualAlarmMap2.wrongs);*/

			//责任人
			var dutyManDataMap = data.dutyManDataMap;
			if(checkNull(dutyManDataMap))
				setDutyMan(dutyManDataMap);

			//加工信息
			var processMsgDataList = data.processMsgDataList;
			if(checkNull(processMsgDataList))
				setProcessMsg(processMsgDataList);

			//设备工艺信息
			if(checkNull(equipOp)){
				$.each(equipOp, function(i) {
					var item = equipOp[i];
					$.each(svgDataArray, function(j) {
						if (item.equipName.indexOf(svgDataArray[j]) != -1) {
							var index = j < 9 ? "0" + (j + 1) : (j + 1);
							var op = svgDocument.getElementById("op" + index);
							op.textContent = item.opName;
						}
					});
				});
			}

			//物料管理			
			var mrlStateList = data.mrlStateList;
			var planCompMap = data.planCompMap;
			if(checkNull(mrlStateList) && checkNull(planCompMap))
				getMrlTableInfo(mrlStateList,planCompMap);

			dateShow();
			if(checkNull(equipStatusKanbanDataMap))
				changeEquipSvgData(equipStatusKanbanDataMap.dataList);
			RBtest(data);
			if(checkNull(equipOEEDataMap))
				equipLine(equipOEEDataMap);
		});
}

//获取固定格式的日期
function getFormatDate(date) {
	var year = date.getFullYear();
	var month = (date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : "0" + (date.getMonth() + 1);
	var day = date.getDate() > 9 ? date.getDate() : "0" + date.getDate();
	var hour = date.getHours() > 9 ? date.getHours() : "0" + date.getHours();
	var minute = date.getMinutes() > 9 ? date.getMinutes() : "0" + date.getMinutes();
	var second = date.getSeconds() > 9 ? date.getSeconds() : "0" + date.getSeconds();
//	if((minute == '30'&& second == '00' ) || (minute == '30'&& second == '30' ))
//	{
//		if(reloadFlag)
//		{
//			window.location.reload();
//			reloadFlag = false;
//		}else{
//			reloadFlag = true;
//		}
//	}
	var formatStr = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
	return formatStr;
}

//时间显示赋值
function dateShow() {
	var timeInterval = setInterval(function() {
		//按秒相加
		nowDate = new Date(Date.parse(nowDate) + (1000));
		var formatStr = getFormatDate(nowDate);
		//$("#nowTime").html(formatStr);
		var nowTime = document.getElementById('nowTime');
		//$api.html(nowTime,formatStr);
		nowTime.innerHTML = formatStr; 
	}, 1000);
}

// SVG
function initSVG(evt) {
	
	if (svgDocument == "") {
		//Svg初始化给html的svgDocument赋值，可外部访问svg对象
		svgDocument = evt.target.ownerDocument;
		// 初始化机台颜色
		RotateSVG();
	}
}

var svgDocument = "";
var svgDataArray;
function changeColor(id, state, text) {
	// -1 离线 灰色;0 空闲黄色;1 运行 绿色;3 报警 红色;
	var png = 'picCNCnull.png';
	var im = svgDocument.getElementById("p" + id);
	var it = svgDocument.getElementById("t" + id);
	if (state == '1') {
		png = 'picCNCgreed.png';
	} else if (state == '3') {
		png = 'picCNCred.png';
	} else if (state == '-1') {
		png = 'picCNCray.png';
	} else if (state == '0') {
		png = 'picCNCyel.png';
	} else {
		png = 'picCNCnull.png';
	}
	im.setAttribute('xlink:href', png);
	it.textContent = text;
};

//获取工作中心
function getWorkCenterCode() {
	return workCenterCode;
}

//改变RGV颜色
function changeColorRobotB(id, state) 
{

	// -1 离线 灰色;0 空闲 黄色;1 运行 蓝色;3 报警 红色;
	var png2 = 'RobotBnull.png';
	var rm = svgDocument.getElementById("rb" + id);
	if (state == '1') 
	{
		png2 = 'RobotBblue.png';
	} else if (state == '3') 
	{
		png2 = 'RobotBred.png';
	} else if (state == '-1') 
	{
		png2 = 'RobotBgray.png';
	} else if (state == '0') 
	{
		png2 = 'RobotByellow.png';
	}
	rm.setAttribute('xlink:href', png2);
};
//改变机器手臂颜色
function changeColorRobotA(id, state) 
{
	// -1 离线 灰色;0 空闲黄色;1 运行 蓝色;3 报警 红色;
	var png3 = 'RobotAnull.png';
	var rm = svgDocument.getElementById("rb" + id);
	if (state == '1') 
	{
		png3 = 'RobotAblue.png';
	} else if (state == '3') 
	{
		png3 = 'RobotAred.png';
	} else if (state == '-1') 
	{
		png3 = 'RobotAgray.png';
	} else if (state == '0') 
	{
		png3 = 'RobotAyellow.png';
	}
	rm.setAttribute('xlink:href', png3);
};
function RBtest(data)
{
  var thisLine= getLineName();
  
  //A
  var data1=[{"ROBOTNAME":"A01","STATUSCODE":"0"},{"ROBOTNAME":"A02","STATUSCODE":"3"},{"ROBOTNAME":"A03","STATUSCODE":"1"},{"ROBOTNAME":"A04","STATUSCODE":"-1"},{"ROBOTNAME":"A05","STATUSCODE":"-1"},{"ROBOTNAME":"A06","STATUSCODE":"1"},{"ROBOTNAME":"A07","STATUSCODE":"1"},{"ROBOTNAME":"A08","STATUSCODE":"1"}];
  //B
  var data2=[{"ROBOTNAME":"-","STATUSCODE":"-"},{"ROBOTNAME":"B02","STATUSCODE":"3"},{"ROBOTNAME":"B03","STATUSCODE":"1"},{"ROBOTNAME":"-","STATUSCODE":"-"},{"ROBOTNAME":"-","STATUSCODE":"-"},{"ROBOTNAME":"E06","STATUSCODE":"1"},{"ROBOTNAME":"-","STATUSCODE":"-"},{"ROBOTNAME":"-","STATUSCODE":"-"},{"ROBOTNAME":"-","STATUSCODE":"-"},{"ROBOTNAME":"B10","STATUSCODE":"3"},{"ROBOTNAME":"B11","STATUSCODE":"-1"}];
  //C
  var data3=[{"ROBOTNAME":"-","STATUSCODE":"-"},{"ROBOTNAME":"B02","STATUSCODE":"3"},{"ROBOTNAME":"-","STATUSCODE":"-"},{"ROBOTNAME":"B04","STATUSCODE":"-1"},{"ROBOTNAME":"-","STATUSCODE":"-"},{"ROBOTNAME":"E06","STATUSCODE":"1"},{"ROBOTNAME":"-","STATUSCODE":"-"},{"ROBOTNAME":"-","STATUSCODE":"-"},{"ROBOTNAME":"-","STATUSCODE":"-"},{"ROBOTNAME":"B10","STATUSCODE":"3"},{"ROBOTNAME":"B11","STATUSCODE":"-1"}];
  //D
  var data4=[{"ROBOTNAME":"-","STATUSCODE":"-"},{"ROBOTNAME":"B02","STATUSCODE":"3"},{"ROBOTNAME":"B03","STATUSCODE":"1"},{"ROBOTNAME":"-","STATUSCODE":"-"},{"ROBOTNAME":"-","STATUSCODE":"-"},{"ROBOTNAME":"E06","STATUSCODE":"1"},{"ROBOTNAME":"-","STATUSCODE":"-"},{"ROBOTNAME":"B08","STATUSCODE":"-1"},{"ROBOTNAME":"-","STATUSCODE":"-"},{"ROBOTNAME":"B10","STATUSCODE":"3"},{"ROBOTNAME":"-","STATUSCODE":"-"}];
  //E
  var data5=[{"ROBOTNAME":"B01","STATUSCODE":"1"},{"ROBOTNAME":"B02","STATUSCODE":"3"},{"ROBOTNAME":"B03","STATUSCODE":"1"},{"ROBOTNAME":"B04","STATUSCODE":"-1"},{"ROBOTNAME":"B05","STATUSCODE":"-1"},{"ROBOTNAME":"E06","STATUSCODE":"1"},{"ROBOTNAME":"B07","STATUSCODE":"1"},{"ROBOTNAME":"B08","STATUSCODE":"-1"},{"ROBOTNAME":"B09","STATUSCODE":"1"},{"ROBOTNAME":"B10","STATUSCODE":"3"},{"ROBOTNAME":"B11","STATUSCODE":"-1"}];
  //F
  var data6=[{"ROBOTNAME":"B01","STATUSCODE":"1"},{"ROBOTNAME":"B02","STATUSCODE":"3"},{"ROBOTNAME":"B03","STATUSCODE":"1"},{"ROBOTNAME":"B04","STATUSCODE":"-1"},{"ROBOTNAME":"B05","STATUSCODE":"-1"},{"ROBOTNAME":"E06","STATUSCODE":"1"},{"ROBOTNAME":"B07","STATUSCODE":"1"},{"ROBOTNAME":"B08","STATUSCODE":"-1"},{"ROBOTNAME":"B09","STATUSCODE":"1"}];
  //G
  var data7=[{"ROBOTNAME":"-","STATUSCODE":"-"},{"ROBOTNAME":"B02","STATUSCODE":"3"},{"ROBOTNAME":"-","STATUSCODE":"-"},{"ROBOTNAME":"B04","STATUSCODE":"-1"},{"ROBOTNAME":"-","STATUSCODE":"-"},{"ROBOTNAME":"E06","STATUSCODE":"1"},{"ROBOTNAME":"B07","STATUSCODE":"1"},{"ROBOTNAME":"-","STATUSCODE":"-"},{"ROBOTNAME":"B09","STATUSCODE":"1"}];
  //H
  var data8=[{"ROBOTNAME":"-","STATUSCODE":"-"},{"ROBOTNAME":"B02","STATUSCODE":"3"},{"ROBOTNAME":"B03","STATUSCODE":"1"},{"ROBOTNAME":"-","STATUSCODE":"-"},{"ROBOTNAME":"B05","STATUSCODE":"-1"},{"ROBOTNAME":"-","STATUSCODE":"-"},{"ROBOTNAME":"-","STATUSCODE":"-"},{"ROBOTNAME":"B08","STATUSCODE":"-1"},{"ROBOTNAME":"B09","STATUSCODE":"1"}];
  //I
  var data9=[{"ROBOTNAME":"-","STATUSCODE":"-"},{"ROBOTNAME":"B02","STATUSCODE":"3"},{"ROBOTNAME":"B03","STATUSCODE":"1"},{"ROBOTNAME":"-","STATUSCODE":"-"},{"ROBOTNAME":"B05","STATUSCODE":"-1"},{"ROBOTNAME":"-","STATUSCODE":"-"},{"ROBOTNAME":"-","STATUSCODE":"-"},{"ROBOTNAME":"B08","STATUSCODE":"-1"},{"ROBOTNAME":"B09","STATUSCODE":"1"},{"ROBOTNAME":"-","STATUSCODE":"-"},{"ROBOTNAME":"-","STATUSCODE":"-"}];
  //J
  var data10=[{"ROBOTNAME":"B01","STATUSCODE":"1"},{"ROBOTNAME":"B02","STATUSCODE":"3"},{"ROBOTNAME":"B03","STATUSCODE":"1"},{"ROBOTNAME":"B04","STATUSCODE":"-1"},{"ROBOTNAME":"B05","STATUSCODE":"-1"},{"ROBOTNAME":"E06","STATUSCODE":"1"},{"ROBOTNAME":"B07","STATUSCODE":"1"},{"ROBOTNAME":"B08","STATUSCODE":"-1"},{"ROBOTNAME":"B09","STATUSCODE":"1"}];
  if("A"==thisLine)
  {
		for (var i = 0; i < data1.length; i++) 
		{
			if (i < 9) {
				changeColorRobotA("0" + (i + 1), data1[i].STATUSCODE);
			} else {
				changeColorRobotA((i + 1), data1[i].STATUSCODE);
			}
		}
	} else if ("B" == thisLine) {
		for (var i = 0; i < data2.length; i++) 
		{
			if (i < 9) 
			{
				changeColorRobotB("0" + (i + 1), data2[i].STATUSCODE);
			} else {
				changeColorRobotB((i + 1), data2[i].STATUSCODE);
			}
		}
	} else if ("C" == thisLine) {
		for (var i = 0; i < data3.length; i++) 
		{
			if (i < 9) 
			{
				changeColorRobotB("0" + (i + 1), data3[i].STATUSCODE);
			} else {
				changeColorRobotB((i + 1), data3[i].STATUSCODE);
			}
		}
	} else if ("D" == thisLine) {
		for (var i = 0; i < data4.length; i++) 
		{
			if (i < 9) 
			{
				changeColorRobotB("0" + (i + 1), data4[i].STATUSCODE);
			} else {
				changeColorRobotB((i + 1), data4[i].STATUSCODE);
			}
		}
	} else if ("E" == thisLine) {
		for (var i = 0; i < data5.length; i++) 
		{
			if (i < 9) 
			{
				changeColorRobotA("0" + (i + 1), data5[i].STATUSCODE);
			} else {
				changeColorRobotA((i + 1), data5[i].STATUSCODE);
			}
		}
	} else if ("F" == thisLine) {
		for (var i = 0; i < data6.length; i++) 
		{
			if (i < 9) 
			{
				changeColorRobotA("0" + (i + 1), data6[i].STATUSCODE);
			} else {
				changeColorRobotA((i + 1), data6[i].STATUSCODE);
			}
		}
	} else if ("G" == thisLine) {
		for (var i = 0; i < data7.length; i++) 
		{
			if (i < 9) 
			{
				changeColorRobotB("0" + (i + 1), data7[i].STATUSCODE);
			} else {
				changeColorRobotB((i + 1), data7[i].STATUSCODE);
			}
		}
	} else if ("H" == thisLine) {
		for (var i = 0; i < data8.length; i++) 
		{
			if (i < 9) 
			{
				changeColorRobotB("0" + (i + 1), data8[i].STATUSCODE);
			} else {
				changeColorRobotB((i + 1), data8[i].STATUSCODE);
			}
		}
	} else if ("I" == thisLine) {
		for (var i = 0; i < data9.length; i++) 
		{
			if (i < 9) 
			{
				changeColorRobotB("0" + (i + 1), data9[i].STATUSCODE);
			} else {
				changeColorRobotB((i + 1), data9[i].STATUSCODE);
			}
		}
	} else if ("J" == thisLine) {
		for (var i = 0; i < data10.length; i++) 
		{
			if (i < 9) 
			{
				changeColorRobotA("0" + (i + 1), data10[i].STATUSCODE);
			} else {
				changeColorRobotA((i + 1), data10[i].STATUSCODE);
			}
		}
	}
}

//获取线名
function getLineName() {
	return workCenterName.substring(0, 1);
}

//机台状态  -1 离线 灰色;0 空闲蓝色;1 运行 绿色;2 暂停 黄色;3 报警 红色;
function changeEquipSvgData(data) {

	var dataArray = $.parseJSON(data);
	//遍历dataArray
	for (var i = 0; i < dataArray.length; i++) 
	{
		for (var j = 0; j < svgDataArray.length; j++) 
		{
			if (dataArray[i].EQUIPNAME.indexOf(svgDataArray[j]) > 0) {			
				if (j < 9) {
					changeColor("0" + (j + 1), dataArray[i].STATUSCODE, getLineName() + svgDataArray[j]);
				} else {
					changeColor((j + 1), dataArray[i].STATUSCODE, getLineName() + svgDataArray[j]);
				}
				break;
			}
		}

	}
}

function RotateSVG() 
{	
var lineA=new Array("02","01","04","03","06","05","08","07","10","09","12","11","14","13","16","15");
    var lineB=new Array("02","01","04","03","06","05","08","07","10","09","12","11","14","13","16","15","18","17","20","19","22","21");
    var lineC=new Array("02","-","04","01","06","03","08","-","10","05","12","07","14","-","16","09","18","11","20","-","22","13");
    var lineD=new Array("-","01","02","03","04","05","-","07","06","09","08","11","-","13","10","15","12","17","-","19","14","21");
    var lineE=new Array("02","01","04","03","06","05","08","07","10","09","12","11","14","13","16","15","18","17","20","19","22","21");
    var lineF=new Array("01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18");
    var lineG=new Array("01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18");
    var lineH=new Array("-","02","01","04","03","06","-","08","05","10","07","12","-","14","09","16","11","18");
    var lineI=new Array("-","01","02","03","04","05","-","07","06","09","08","11","-","13","10","15","12","17");
    var lineJ=new Array("01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18");
    var lineK=new Array("01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18");
	var line = getLineName();
	if (line == "A") {
		svgDataArray = lineA;
	} else if (line == "B") {
		svgDataArray = lineB;
	} else if (line == "C") {
		svgDataArray = lineC;
	} else if (line == "D") {
		svgDataArray = lineD;
	} else if (line == "E") {
		svgDataArray = lineE;
	} else if (line == "F") {
		svgDataArray = lineF;
	} else if (line == "G") {
		svgDataArray = lineG;
	} else if (line == "H") {
		svgDataArray = lineH;
	} else if (line == "I") {
		svgDataArray = lineI;
	} else if (line == "J") {
		svgDataArray = lineJ;
	} else if (line == "K") {
		svgDataArray = lineK;
	}
	//遍历dataArray
	for (var i = 0; i < svgDataArray.length; i++) 
	{
		if (svgDataArray[i] != "-") {
			if (i < 9) {
				changeColor("0" + (i + 1), "-1", line + svgDataArray[i]);
			} else {
				changeColor((i + 1), "-1", line + svgDataArray[i]);
			}
		}
	}
   var svgTag = document.getElementById("svg3015");
}

//加工信息
function setProcessMsg(data) {
	//转换jason格式
	var dataObj = eval(data);
	$("#addElement").children().remove();
	//遍历数组
	$.each(dataObj, function(i) {
		var item = dataObj[i];
		//创建一个div标签
		var $DIV = $("<div></div>");
		var len = dataObj.length < 3 ? 3 : dataObj.length;
		//设置div的样式宽度，高度
		var height = ($("#opPanel").height() - $("#opTitle").height() - 4) / len;
		$DIV.height(height);
		
		var imgHeigh = height - 38;
		var imgWidth = $("#opPanel").width();
		//创建两个h5标签
		//var $H51 = $("<h5 class='code-style2 col-xs-6 col-sm-6 col-md-6 col-lg-6 ' id='code-style3-md'>工序编码：" + item.opCode + "</h5>");
		var $H52 = $("<h5 class='code-style2 col-xs-6 col-sm-6 col-md-12 col-lg-7 ' id='code-style3-md'>工序名称：" + item.opName + "</h5>");

		//创建一个img标签,并且给一个div标签包裹
		var $IMG = $("<img col-xs-3 col-sm-3 col-md-3 col-lg-3 src='" + "http://" + serverIp + ":" + serverPort
				+ "/" + serverProject + "/" + item.opImg + "' />");
		//设置img的样式宽度，高度
		$IMG.width(imgWidth);
		$IMG.height(imgHeigh);

		//$IMG.height(imgHeigh);
		//将三个标签添加到div标签下
		//$DIV.append($H51);
		$DIV.append($H52);
		$DIV.append($IMG);
		//将div标签添加到父div标签中
		$("#addElement").append($DIV);
	});
}

//设备稼动率 
function equipLine(data) {
	var xAxisData = data.xAxis;
	for(var i = 0;i<xAxisData.length;i++)
	{
		xAxisData[i] = xAxisData[i].substring(5);
	}
	var option = {
		tooltip : {
			trigger : 'axis'
		},
		grid:{
			top : '10%'
		},
		legend : {
			data : data.legend //['白班','晚班']
		},
		calculable : true,
		xAxis : [{
			type : 'category',
			splitLine: {show:false},
			axisLabel : {
				'interval' : 0
			},
			data : xAxisData
		}],
		yAxis : [{
			type : 'value',
			axisLabel : {
				//formatter : '{value} %'
			},
			interval:0,
			axisLine : {
			}
		}],
		series : data.series
	};
	equipLineChart.setOption(option);
}
	
//设备状态
function setEquipmentState(data){
	if(data.alarm == undefined){
		$("#alarm").html("报警："+0);
	}else{
		$("#alarm").html("报警：" + data.alarm);
	}
	
	if(data.run == undefined){
		$("#run").html("运行："+0);
	}else{
		$("#run").html("运行：" + data.run);
	}
	
	if(data.idle == undefined){
		$("#idle").html("待机："+0);
	}else{
		$("#idle").html("待机：" + data.idle);
	}
	
	if(data.disconnect == undefined){
		$("#disconnect").html("停机："+0);
	}else{
		$("#disconnect").html("停机：" + data.disconnect);
	}
}

// 通知模板状态
function setTvStata(data) {
	var divHeight = $("#body").height() + $("#bottom").height();
	
	$(".lay").height(divHeight + "px");
	if (data == 0) {
		$("#lay").hide();
		$("#body").show();
		$("#bottom").show();
	} else {
		$("#lay").show();// 显示div
		$("#body").hide();
		$("#bottom").hide();
	}
}


// 机型
function setEquipType(data) {
	if (data == undefined) {
		$("#equipmentModel").html("机型：");
	} else {
		$("#equipmentModel").html("机型：" + data);
	}
}


//通知模板内容
function setTvContent(data){
	$("#equipmentModel2").children().remove();
	$("#equipmentModel2").append(data);
}

//物料信息（表格）
function getMrlTableInfo(data,data2) {
	// 转换jason格式
	var dataObj = eval(data);
	var dataObj2 = eval(data2);
	$("#percent").html(dataObj2.percent);
	$("#planQty").html("计划数：" + dataObj2.planQty);
	$("#wipQty").html("捡料数：" + dataObj2.wipQty);
	$("#transitQty").html("派工数：" + dataObj2.transitQty);
	$("#finishQty").html("完工数：" + dataObj2.finishQty);

	// 遍历数组
	$.each(dataObj, function(j,item) {
		var opName_=$("#opName_"+j);
		var opTransit_=$("#opTransit_"+j);
		var opFinish_=$("#opFinish_"+j);
		$(opName_).text(item.opName);
		$(opTransit_).text(item.opTransit);
		$(opFinish_).text(item.opFinish);

	});
}

// 产线负责人
function setDutyMan(data) {
	/* var director = data.director;
	if (director == undefined) {
		$("#director").text("姓名：");
	} else {
		$("#director").text("姓名：" + data.director);
	}
	var directorTel = data.directorTel;
	if (directorTel == undefined) {
		$("#directorTel").text("电话：");
	} else {
		$("#directorTel").text("电话：" + directorTel);
	}
	
	$("#directorImg").attr("src", "http://" + serverIp + ":" + serverPort + "/" + serverProject + "/" + data.directorImgContent);*/
	var leader = data.leader;
	if (leader == undefined) {
		$("#director").text("姓名：");
	} else {
		$("#director").text("姓名：" + data.leader);
	}
	var leaderTel = data.leaderTel;
	if (leaderTel == undefined) {
		$("#directorTel").text("电话：");
	} else {
		$("#directorTel").text("电话：" + leaderTel);
	}

	$("#directorImg").attr("src","http://" + serverIp + ":" + serverPort + "/" + serverProject + "/" + data.leaderImgContent);
}
/*
//异常处理
function setLiValue2(wrongs) 
{
  	var worngArray = eval(wrongs);
  	wrongIndex = -1;
  	wrongSize = -1;
  	if (wrongs == "" || wrongs == null) {
    	$("#exception-content").children().remove();
    	$("#exception-content").append("<li><p class='lead'>无异常</p></li>");
    	
    	$("#deal-person").children().remove();
    	$("#deal-person").append("<li><p class='lead'></p></li>");
  	} else {
    	$("#exception-content").children().remove();
    	$("#deal-person").children().remove();
    	var content = "";
    	var personId = "";
    	var dutyName = "";
    	//var worngNums = worngArray.length >= 2 ? 2 : worngArray.length;
    	var worngNums = worngArray.length;
    	for (var i = 0; i < worngNums; i++) 
    	{         	
			personId = worngArray[i].dutyId;
			content = worngArray[i].workCellName + " " + worngArray[i].exceptionTypeName;
          	dutyName = worngArray[i].dutyName;
          	$("#exception-content").append("<li><a href='#' class='lead'>"+content+"</a></li>");        	
          	if(worngArray[i].dutyName!=null)
          	{         	        		
          		$("#deal-person").append("<li><a href='#' class='lead'>"+dutyName+"</a></li>");
          	}else{
          		$("#deal-person").append("<li><a href='#' class='lead'>"+personId+"</a></li>");
          	}
		}
	}
  	$('#exception-content').liMarquee({
        direction: 'up',
        scrollamount: scrollamount
    });
  	
  	$('#deal-person').liMarquee({
        direction: 'up',
        scrollamount: scrollamount
    });
}*/


	//异常处理（获取最近一条异常信息）
	function setLiValue(wrongs) {
	var worngArray = eval(wrongs);
	wrongIndex = -1;
	wrongSize = -1;
	if (wrongs == "" || wrongs == null) {
		$("#exception-content").children().remove();
		$("#exception-content").append("<li><p class='lead'>无异常</p></li>");

		$("#deal-person").children().remove();
		$("#deal-person").append("<li><p class='lead'></p></li>");
	} else {
		$("#exception-content").children().remove();
		$("#deal-person").children().remove();
		var content = "";
		var personId = "";
		var dutyName = "";
		//var worngNums = worngArray.length >= 2 ? 2 : worngArray.length;
		var worngNums = worngArray.length;
		for (var i = 0; i < worngNums; i++) {
			personId = worngArray[i].dutyId;
			content = worngArray[i].workCellName + " " + worngArray[i].exceptionTypeName;
			dutyName = worngArray[i].dutyName;
			$("#exception-content").append("<li><a href='#' class='lead'>" + content + "</a></li>");
			/*if (worngArray[i].dutyName != null) {
				$("#deal-person").append("<li><a href='#' class='lead'>" + dutyName + "</a></li>");
			} else {
				$("#deal-person").append("<li><a href='#' class='lead'>" + personId + "</a></li>");
			}*/
		}
	}

}


//消息日志
var logTime = (new Date()).toLocaleString();
var errorTime = (new Date()).toLocaleString();
function getLog(){
    alert("接收:"+logTime+"\n错误:"+errorTime);
}

function changeLogo(){
	logTime= (new Date()).toLocaleString();
	var logoSrc = $("#Epichus-logo1")[0].src;
	var indexStr = logoSrc.indexOf("logo-right1");
	var indexStr1 = logoSrc.indexOf("logo-right2");
	if(indexStr != -1)
	{
		$("#Epichus-logo1").attr('src','../image/logo-right2.png');
	}
	if(indexStr1 != -1)
	{
		$("#Epichus-logo1").attr('src','../image/logo-right1.png');
	}
}

var msgUrl = "ws://" + serverIp + ":" + serverPort + "/" + serverProject + "/webmsg/";
function onMessage(response){
	changeLogo();
	var message = response.responseBody;
	message = atmosphere.util.parseJSON(message);
	var msgData = $.parseJSON(message.text);
	//时间ajax获取一次即可 nowDate = msgData.nowDate;
	var equipStatusKanbanDataMap = msgData.equipStatusKanbanDataMap;
	var equipOEEDataMap = msgData.equipOEEDataMap;
	var mrl = msgData.mrl;//机型
	var syncTime = msgData.syncTime;
	var syncEchart = msgData.syncEchart;
	var syncReload = msgData.syncReload;
	var syncTvContent = msgData.syncTvContent === 'true';
	var syncResourcePlan = msgData.syncResourcePlan === 'true';
	var syncLineDirector = msgData.syncLineDirector === 'true';
	var syncUnusualAlarm = msgData.syncUnusualAlarm === 'true';
	
	log( "syncTime:"+syncTime
		+"  syncTvContent:"+syncTvContent
		+"  syncResourcePlan:"+syncResourcePlan
		+"  syncLineDirector:"+syncLineDirector
		+"  syncUnusualAlarm:"+syncUnusualAlarm);
		
	if(syncTime){
		log("syncTime has done!");
		nowDate = msgData.nowDate;
	}
	
	if(syncReload){
		log("reload page has done!");		
		window.location.reload();
	}
		
	//通知模板
	var tvState = msgData.tvState;
	setTvStata(tvState);
	if(tvState==1){//notice
		var tvContent = msgData.tvContent;		
		setTvContent(tvContent);		
		return;
	}
	
	if (mrl == undefined) {
		$("#equipmentModel").html("机型：");
	} else {
		$("#equipmentModel").html("机型：" + mrl);
	}
	/*
	// 异常类容
	var unusualAlarmMap2 = msgData.unusualAlarmMap;
	if (null != unusualAlarmMap2){
		setLiValue2(unusualAlarmMap2.wrongs);
	}*/
	
	// 异常类容(获取最近一次的异常信息)
	var unusualAlarmMap = msgData.unusualAlarmMap2;
	if (null != unusualAlarmMap){
		setLiValue(unusualAlarmMap.wrongs);
	}
	
	var uqcDataMap = msgData.uqcDataMap;
	if (null != uqcDataMap){
		uqcChartInit(uqcDataMap);
	}
	
	if (null != equipStatusKanbanDataMap) {
		changeEquipSvgData(equipStatusKanbanDataMap.dataList);
	}
	
	//设备稼动率
	if (null != equipOEEDataMap && null != equipLineChart) {
		equipLine(equipOEEDataMap);
	}
	
	// 工序名称
	var equipOp = msgData.equipOp;	
	if (syncResourcePlan) {
		log("syncResourcePlan equipOp has done!");
		$.each(equipOp, function(i) {
			var item = equipOp[i];
			$.each(svgDataArray, function(j) {
				if (item.equipName.indexOf(svgDataArray[j]) != -1) {
					var index = j < 9 ? "0" + (j + 1) : (j + 1);
					var op = svgDocument.getElementById("op" + index);
					op.textContent = item.opName;
				}
			});
		});
	}
	
	//物料管理	
	var mrlStateList = msgData.mrlStateList;
	var planCompMap = msgData.planCompMap;
	if(checkNull(mrlStateList) && checkNull(planCompMap))
		getMrlTableInfo(mrlStateList, planCompMap); 
	
	//加工信息
	var processMsgDataList = msgData.processMsgDataList;
	if(syncResourcePlan){
		log("syncResourcePlan processMsgDataList has done!");
		setProcessMsg(processMsgDataList);
	}
	
	//责任人
	var dutyManDataMap = msgData.dutyManDataMap;
	if(syncLineDirector && checkNull(dutyManDataMap)){
		log("syncLineDirector has done!");
		setDutyMan(dutyManDataMap);
	}
	
	//设备状态
	var stateMap = msgData.stateMap;
	setEquipmentState(stateMap);
	
 }
function onError(response){
	changeLogo();
	errorTime= (new Date()).toLocaleString()+"-E:"+JSON.stringify(response);
}

function checkNull(data) {
	if (data != null && data !== undefined) {
		return true;
	}

	return false;
}

function log(info){
	if(isDebug)
		console.log(new Date() + info);
	//将日志写入文件
//	var fs = api.require('fs');
//	fs.open({
//	    path: 'fs://'+fileName,
//	    flags: 'read_write'
//	}, function(ret, err) {
//	    if (ret.status) {
//	        var fdStr = ret.fd;
//	        
//	        fs.write({
//			    fd: fdStr,
//			    data: info,
//			    offset: 0
//			}, function(ret, err) {
//			    if (ret.status) {
//			        alert(JSON.stringify(ret));
//			    } else {
//			        alert(JSON.stringify(err));
//			    }
//			});
//	        
//	    } else {
//	        alert(JSON.stringify(err));
//	    }
//	});
}

function initWebSocketRequest() {
	initAtmosphere(msgUrl + showModul + "+" + type + "+" + workCenterGid + "+" + userName, onMessage, onError);
}

initWebSocketRequest(); 

